import * as React from "react";
import { Row, Col, Modal, Spin, message } from "antd";
import ReactEcharts from "echarts-for-react";
import moment from "moment";
import DepartmentMessage from "./compontents/DepartmentMessage";
import Condition from "./compontents/Condition";
import ConditionTable from "./compontents/ConditionTable";
import { analysis } from "../ServeApi";

import { AjaxData } from "../../../../data/interface/publicInterface";
import "./index.less";
export interface CompareAnalysisProps {
  loading: boolean;
}

export interface CompareAnalysisState {}

class CompareAnalysis extends React.Component<
  CompareAnalysisProps,
  CompareAnalysisState
> {
  public checkedKeys: string[] = [];
  private dataSouce: any = null;
  private energyType: number = 1;
  private option: any = {};
  private columns: any[] = [
    {
      title: "名称",
      width: 100,
      dataIndex: "name",
      key: "name",
      fixed: "left",
    },
  ];
  state = { loading: false };
  render() {
    return (
      <div className="BuildingCompareAnalysis">
        <Row>
          <Col span={24} style={{ paddingBottom: 12 }}>
            <Condition
              onSubmit={(data: any) => {
                this.getCondition(data);
              }}
            />
          </Col>
          <Col span={6} style={{ paddingRight: 12 }}>
            <DepartmentMessage
              onSelect={(sele: string[]) => {
                this.selectDepartments(sele);
              }}
            />
          </Col>
          <Col span={18}>
            <Row>
              <Col span={24}>
                <div className="rowcon_body">
                  <Spin spinning={this.state.loading}>
                    <ReactEcharts
                      option={this.option}
                      notMerge={true}
                      lazyUpdate={true}
                      style={{ height: 457 }}
                      // theme="dark"
                    />
                  </Spin>
                </div>
              </Col>
              <Col span={24} style={{ paddingTop: 16 }}>
                <Spin spinning={this.state.loading}>
                  <ConditionTable
                    columns={this.columns}
                    dataSouce={this.dataSouce}
                  />
                </Spin>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>
    );
  }
  //获取选中的部门回调
  selectDepartments(sele: string[]) {
    this.checkedKeys = sele;
    this.forceUpdate();
  }
  //获取筛选条件 回调
  getCondition(data: any) {
    this.energyType = data.type;
    this.updateDataSouce(data);
    this.forceUpdate();
  }
  //条件数据更新
  updateDataSouce(data: any) {
    let pream = {
      energyType: data.type,
      idList: this.checkedKeys,
      time: moment(data.dateString).valueOf(),
    };
    if (this.checkedKeys.length > 0) {
      this.analysis(pream);
    } else {
      message.error("缺少必要的参数“部门”");
    }
  }
  //生成echarts对象
  getWarnOption(dataScouse: any) {
    let str = this.energyType === 1 ? "kW·h" : "t";
    return {
      xAxis: {
        type: "category",
        data: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
      },
      yAxis: {
        name: "单位：" + str,
        splitLine: {
          //网格线
          show: true,
          lineStyle: {
            color: "#ECECEC",
          },
        },
        type: "value",
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "4%",
        containLabel: true,
      },
      legend: { left: "center", data: ["本年", "去年"] },
      color: ["#1890FF", "#5AD8A6"],
      series: [
        {
          name: "本年",
          data: dataScouse.list,
          type: "bar",
          showBackground: true,
          backgroundStyle: {
            color: "rgba(180, 180, 180, 0.2)",
          },
        },
        {
          name: "去年",
          data: dataScouse.compareList,
          type: "bar",
          showBackground: true,
          backgroundStyle: {
            color: "rgba(180, 180, 180, 0.2)",
          },
        },
      ],
    };
  }
  toPercent(point) {
    var str = Number(point * 100).toFixed(1);
    str += "%";
    return str;
  }
  //格式化表格头部，数据
  formattingDataSouce(data: any, energyType: number) {
    let dataSouce: any[] = [];
    let energy: string = energyType === 1 ? "电" : "水";
    let name: string = "";
    for (let key in data) {
      let obj = {};
      let coumon: any[] = [
        {
          title: "名称",
          width: 100,
          dataIndex: "name",
          key: "name",
          fixed: "left",
        },
      ];
      data[key].map((list: any, index: number) => {
        obj["Column" + index] = list;
        coumon.push({
          title: index + 1 + "月",
          dataIndex: "Column" + index,
          key: "Column" + index,
          width: 150,
        });
        return list;
      });
      this.columns = coumon;
      switch (key) {
        case "compareList":
          name = "去年用" + energy;
          break;
        case "list":
          name = "今年用" + energy;
          break;
        default:
          break;
      }
      obj["name"] = name;
      dataSouce.push(obj);
    }
    let { compareList, list } = data;
    let obj2: any = {};
    list.map((item: any, index: number) => {
      let str: string = this.toPercent(
        compareList[index]
          ? (item - compareList[index]) / compareList[index]
          : 0
      );
      obj2["Column" + index] = str;
      return str;
    });
    obj2.name = "同比(%)";
    dataSouce.push(obj2);

    this.dataSouce = dataSouce;
  }
  /**请求数据 */
  async analysis(pream) {
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await analysis(JSON.stringify(pream)).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.formattingDataSouce(json.data, pream.energyType);
        _this.option = _this.getWarnOption(json.data);
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default CompareAnalysis;
